" Plugin Settings
set nocompatible  "去掉讨厌的有关vi一致性模式，避免以前版本的一些bug和局限
filetype off

call plug#begin()
" 设置包括vundle和初始化相关的runtime path
" set rtp+=~/.vim/bundle/Vundle.vim
" call vundle#begin()
" 另一种选择, 指定一个vundle安装插件的路径
"call vundle#begin('~/some/path/here')

" 让vundle管理插件版本,必须
" Plug 'VundleVim/Vundle.vim'

" 以下范例用来支持不同格式的插件安装.
" 请将安装插件的命令放在vundle#begin和vundle#end之间.
" Github上的插件
" 格式为 Plugin '用户名/插件仓库名'
" Plugin 'tpope/vim-fugitive'
" 来自 http://vim-scripts.org/vim/scripts.html 的插件
" Plugin '插件名称' 实际上是 Plugin 'vim-scripts/插件仓库名' 只是此处的用户名可以省略
" Plugin 'L9'
" 由Git支持但不再github上的插件仓库 Plugin 'git clone 后面的地址'
" Plugin 'git://git.wincent.com/command-t.git'
" 本地的Git仓库(例如自己的插件) Plugin 'file:///+本地插件仓库绝对路径'
" Plugin 'file:///home/gmarik/path/to/plugin'
" 插件在仓库的子目录中.
" 正确指定路径用以设置runtimepath. 以下范例插件在sparkup/vim目录下
" Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
" 安装L9，如果已经安装过这个插件，可利用以下格式避免命名冲突
" Plugin 'ascenator/L9', {'name': 'newL9'}

Plug 'christoomey/vim-tmux-navigator'
Plug 'ap/vim-buftabline'
Plug 'mzlogin/vim-markdown-toc'
" Markdown TOC 生成 https://mazhuang.org/2015/12/19/vim-markdown-toc/
" :GenTocGFM 在光标处生成 GFM 风格的 Table of Contents
" :RemoveToc 删除插件生成的 TOC

Plug 'majutsushi/tagbar'
" Plugin 'lvht/tagbar-markdown'
Plug 'scrooloose/nerdtree'
let NERDTreeMinimalUI=1
let NERDTreeQuitOnOpen=1
" let NERDTreeWinPos='left'
" let NERDTreeShowBookmarks=1
" let NERDTreeWinSize=31
" let NERDTreeChDirMode=1

Plug 'lervag/vimtex'

Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'mhinz/vim-signify' " VCS 文件修改情况显示
Plug 'tpope/vim-fugitive' " vim 中使用 git 的增强插件
Plug 'fatih/vim-go', { 'do': ':GoUpdateBinaries' } " golang


" 缩进线条
Plug 'Yggdroot/indentLine'
let g:indentLine_showFirstIndentLevel = 1
let g:indentLine_setColors = 0

Plug 'leafOfTree/vim-vue-plugin' " vue

" 你的所有插件需要在下面这行之前
call plug#end()

""""""""""""""""" Plugin Configure
" let g:vimtex_compiler_latexmk = {}
" let g:vimtex_imaps_leader = '@'
let g:tex_flavor = 'latex'


"""""""""""""""""


filetype plugin indent on    " 必须 加载vim自带和插件相应的语法和文件类型相关脚本
" 忽视插件改变缩进,可以使用以下替代:
"filetype plugin on
"
" 常用的命令
" :PluginList       - 列出所有已配置的插件
" :PluginInstall     - 安装插件,追加 `!` 用以更新或使用 :PluginUpdate
" :PluginSearch foo - 搜索 foo ; 追加 `!` 清除本地缓存
" :PluginClean      - 清除未使用插件,需要确认; 追加 `!` 自动批准移除未使用插件
"
" 查阅 :h vundle 获取更多细节和wiki以及FAQ
" 将你自己对非插件片段放在这行之后


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

" Tagbar Markdown
let g:tagbar_type_markdown = {
    \ 'ctagstype': 'markdown',
    \ 'ctagsbin' : '/home/zhb/script/markdown2ctags.py',
    \ 'ctagsargs' : '-f - --sort=yes',
    \ 'kinds' : [
        \ 's:sections',
        \ 'i:images'
    \ ],
    \ 'sro' : '|',
    \ 'kind2scope' : {
        \ 's' : 'section',
    \ },
    \ 'sort': 0,
\ }
" let g:tagbar_type_markdown = {
"         \ 'ctagstype' : 'markdown',
"         \ 'kinds' : [
"                 \ 'h:headings',
"         \ ],
"     \ 'sort' : 0
" \ }

" au VimEnter * silent NERDTree " 启动时自动开启 NERDTree (autocmd == au)
" from
" https://stackoverflow.com/questions/29973424/open-nerdtree-when-vim-is-opened-without-args-but-not-with
autocmd StdinReadPre * let g:isReadingFromStdin = 1
autocmd VimEnter * if !argc() && !exists('g:isReadingFromStdin') | NERDTree | endif


"""""""""""""""""""""""" coc.vim config
" TextEdit might fail if hidden is not set.
set hidden

" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience.
set updatetime=300

" Don't pass messages to |ins-completion-menu|.
set shortmess+=c

" Use tab for trigger completion with characters ahead and navigate.
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config.
inoremap <silent><expr> <TAB>
      \ pumvisible() ? "\<C-n>" :
      \ <SID>check_back_space() ? "\<TAB>" :
      \ coc#refresh()
inoremap <expr><S-TAB> pumvisible() ? "\<C-p>" : "\<C-h>"

function! s:check_back_space() abort
  let col = col('.') - 1
  return !col || getline('.')[col - 1]  =~# '\s'
endfunction

" Use <c-space> to trigger completion.
if has('nvim')
  inoremap <silent><expr> <c-space> coc#refresh()
else
  inoremap <silent><expr> <c-@> coc#refresh()
endif

function! s:check_back_space() abort
  let col = col('.') - 1
  return !col || getline('.')[col - 1]  =~# '\s'
endfunction

" Use <c-space> to trigger completion.
if has('nvim')
  inoremap <silent><expr> <c-space> coc#refresh()
else
  inoremap <silent><expr> <c-@> coc#refresh()
endif

" Use <cr> to confirm completion, `<C-g>u` means break undo chain at current
" position. Coc only does snippet and additional edit on confirm.
" <cr> could be remapped by other vim plugin, try `:verbose imap <CR>`.
if exists('*complete_info')
  inoremap <expr> <cr> complete_info()["selected"] != "-1" ? "\<C-y>" : "\<C-g>u\<CR>"
else
  inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
endif

"""""""""""""""""""""""""""""""""""""""""""""""""

set t_Co=256 " 开启 256颜色
set background=dark
" colorscheme solarized
syntax enable
set fdm=syntax " 代码折叠 manual indent expr syntax diff marker
" set syntax=whitespace
" set list

""""""""""""""""""""""""""""""""""""""""""""""""" Functions
" Get Git Branch Name
function! GitBranch()
  return system("git rev-parse --abbrev-ref HEAD 2>/dev/null | tr -d '\n'")
endfunction

""""""""""""""""""""""""""""""""""""""""""""""""" Set Show Style
set listchars=tab:▸\ ,trail:~,extends:>,precedes:<,space:␣ " ,eol:¬
" set lines=24 columns=80	" 设定窗口大小
set nu		" 显示行号
set rnu     " 相对行号
set guifont=Droid_Sans_Mono:h11:cANSI	" 设置字体
set guifontwide=WenQuanYi_Micro_Hei:h11:cANSI
set showcmd	" 显示输出的命令
" fillchars http://vimdoc.sourceforge.net/htmldoc/options.html#%27fillchars%27
set fillchars+=vert:│ " |(U+007C)│(U+2502)

""""""""""""""""""""""""""""""""""""""""""""""""" Highlight Color
hi StatusLine cterm=bold ctermbg=238 ctermfg=11
hi StatusLineNC cterm=NONE ctermbg=238 ctermfg=NONE
""""""" CursorLine Color
" https://stackoverflow.com/questions/8247243/highlighting-the-current-line-number-in-vim
hi clear CursorLine
hi CursorLine cterm=NONE ctermbg=238 ctermfg=NONE
hi CursorLineNR cterm=bold ctermbg=238 ctermfg=226
hi LineNR ctermbg=236
set cursorline
""""""" VertSplit Color
hi VertSplit cterm=reverse ctermbg=243 ctermfg=236
""""""" Tab Color
hi TabLine cterm=NONE ctermfg=229 ctermbg=237 " Buffer not currently visible
hi TabLineSel cterm=bold ctermfg=253 ctermbg=238 " Buffer shown in current window
hi TabLineFill cterm=NONE ctermbg=237 " Empty area
hi PmenuSel cterm=NONE ctermfg=229 ctermbg=240 " Buffer shown in other window

""""""""""""""""""""""""""""""""""""""""""""""""" Status Line
" set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [POS=%l,%v][%p%%]\ %{strftime(\"%d/%m/%y\ -\ %H:%M\")}   "状态行显示的内容

" Status bar begin, More help in :help statusline
" For highlight group see :help highlight-groups
" highlight-args highlight-default cterm-colors
" :hi[ghlight] [default] {group-name} {key}={arg} ..
" From https://dustri.org/b/lightweight-and-sexy-status-bar-in-vim.html
function! ActiveStatus()
	let statusline=""
	let statusline.="%#DiffAdd#%{(mode()=='n')?'\ \ NORMAL\ ':''}"
	let statusline.="%#DiffChange#%{(mode()=='i')?'\ \ INSERT\ ':''}"
	let statusline.="%#DiffDelete#%{(mode()=='r')?'\ \ RPLACE\ ':''}"
	let statusline.="%#Cursor#%{(mode()=='v')?'\ \ VISUAL\ ':''}"
	let statusline.="\ %n\ "          " buffer number
	let statusline.="%#Visual#"       " colour
	let statusline.="%{&paste?'\ PASTE\ ':''}"
	let statusline.="%{&spell?'\ SPELL\ ':''}"
	let statusline.="%#CursorIM#"     " colour
	let statusline.="%R"                        " readonly flag
	let statusline.="%M"                        " modified [+] flag
	let statusline.="%#Cursor#"               " colour
	let statusline.="%#StatusLine#"     " colour
	let statusline.="\ %t\ "                  " short file name
	let statusline.="%#Visual#"     " colour
	let statusline.="\ %{toupper(strlen(&fenc)?&fenc:'none')}\ " " file encoding
	let statusline.="%{toupper(&ff)}\ "              "file format
	let statusline.="%#StatusLine#"		" colour
	let statusline.="%="                          " right align
	let statusline.="%#CursorIM#"     " colour
	let statusline.="\ %{FugitiveStatusline()}\ "               " git branch
	let statusline.="%#Visual#" " colour
	let statusline.="\ %Y\ "                  " file type
	let statusline.="%#CursorIM#"     " colour
	let statusline.="\ %3l:%-2c\ "        " line + column
	let statusline.="%#Cursor#"       " colour
	let statusline.="\ %3p%%\ "               " percentage
	return statusline
endfunction
function! InactiveStatus()
	let statusline=""
	let statusline.="%#DiffAdd#%{(mode()=='n')?'\ \ NORMAL\ ':''}"
	let statusline.="%#DiffChange#%{(mode()=='i')?'\ \ INSERT\ ':''}"
	let statusline.="%#DiffDelete#%{(mode()=='r')?'\ \ RPLACE\ ':''}"
	let statusline.="%#Cursor#%{(mode()=='v')?'\ \ VISUAL\ ':''}"
	let statusline.="\ %n\ "          " buffer number
	let statusline.="%#Visual#"       " colour
	let statusline.="%{&paste?'\ PASTE\ ':''}"
	let statusline.="%{&spell?'\ SPELL\ ':''}"
	let statusline.="%#CursorIM#"     " colour
	let statusline.="%R"                        " readonly flag
	let statusline.="%M"                        " modified [+] flag
	let statusline.="%#Cursor#"               " colour
	let statusline.="%#StatusLineNC#"     " colour
	let statusline.="\ %t\ "                  " short file name
	let statusline.="%#Visual#"     " colour
	let statusline.="\ %{toupper(strlen(&fenc)?&fenc:'none')}\ " " file encoding
	let statusline.="%{toupper(&ff)}\ "              "file format
	let statusline.="%#StatusLineNC#"		" colour
	let statusline.="%="                          " right align
	let statusline.="%#Visual#" " colour
	let statusline.="\ %Y\ "                  " file type
	let statusline.="%#CursorIM#"     " colour
	let statusline.="\ %3l:%-2c\ "        " line + column
	let statusline.="%#Cursor#"       " colour
	let statusline.="\ %3p%%\ "               " percentage
	return statusline
endfunction
" Status bar end

set statusline=%!ActiveStatus()
augroup status
	autocmd!
	autocmd WinEnter * setlocal statusline=%!ActiveStatus()
	autocmd WinLeave * setlocal statusline=%!InactiveStatus()
augroup END

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" Encodings
set fencs=utf-8,ucs-bom,shift-jis,gb18030,gbk,gb2312,cp936
set termencoding=utf-8
set encoding=utf-8
" set fileencodings=ucs-bom,utf-8,cp936
set fileencoding=utf-8


set tabstop=4
set softtabstop=4
set shiftwidth=4
set noexpandtab	" 不要用空格代替Tab
set smarttab	" 在行和段开始处使用制表符
set history=1000	" 历史记录数

set laststatus=2	" 总是显示状态行
set cmdheight=2	" 命令行（在状态下）的高度

autocmd BufWritePost $MYVIMRC source $MYVIMRC " 配置立即生效

set splitbelow
set splitright

" To prevent conceal in LaTeX files
let g:tex_conceal = ''
" To prevent conceal in any file
set conceallevel=0

""""""""""""""""""""""""""""""""""""""""""""""""" Key Bindings
" <leader>
let mapleader=" "
nmap <leader>wq :wq<CR>
nmap <leader>w :w<CR>
nmap <leader>q :q<CR>
nmap <silent> <leader>e :NERDTreeToggle<CR>
nmap <leader>t :tabnew<CR>
nmap <silent> <leader>p :set invpaste<CR>
nmap <leader>b :ls<CR>:b<Space>
nmap <leader>g :TagbarToggle<CR>
nnoremap <Leader>c :set cursorline! cursorcolumn!<CR>

nnoremap <C-J> <C-W><C-J>
nnoremap <C-K> <C-W><C-K>
nnoremap <C-L> <C-W><C-L>
nnoremap <C-H> <C-W><C-H>

nnoremap <C-N> :bnext<CR>
nnoremap <C-P> :bprev<CR>

noremap <F5> :set list!<CR>
inoremap <F5> <C-o>:set list!<CR>
cnoremap <F5> <C-c>:set list!<CR>

" 中文输入法 normal 下自动关闭 
" 来源 https://www.jianshu.com/p/d6067b47cec4 并加以修改
let g:input_toggle = 0 " 全局设置 是否在进入 vim 时打开输入法 1: 是 0: 否
function! Fcitx2en()
	let b:input_status = system("fcitx-remote")
	if b:input_status == 2
		let b:input_toggle = 1
		let l:a = system("fcitx-remote -c")
	endif
endfunction

function! Fcitx2zh()
	let b:input_status = system("fcitx-remote")
	if !exists("b:input_toggle")
		let b:input_toggle = g:input_toggle
	endif
	if b:input_status != 2 && b:input_toggle == 1
		let l:a = system("fcitx-remote -o")
		let b:input_toggle = 0
	endif
endfunction

set timeoutlen=350
" autocmd InsertLeave * call Fcitx2en()
" autocmd InsertEnter * call Fcitx2zh()

" set showtabline=2  " 始终显示 Tab 行
" more customization to see on https://stackoverflow.com/questions/7238113/customising-the-colours-of-vims-tab-bar
" Tabline Customize from https://www.reddit.com/r/vim/comments/22ala7/vim_custom_tabline/
if exists("+showtabline")

" Rename tabs to show tab number.
" (Based on http://stackoverflow.com/questions/5927952/whats-implementation-of-vims-default-tabline-function)

function! MyTabLine()
    let s = ''
    let t = tabpagenr()
    let i = 1
    while i <= tabpagenr('$')
        let buflist = tabpagebuflist(i)
        let winnr = tabpagewinnr(i)
        let s .= '%' . i . 'T'
        let s .= (i == t ? '%1*' : '%2*')

        " let s .= (i == t ? '%#TabLineSel#' : '%#TabLine#')
        " let s .= ' '
        let s .= (i == t ? '%#TabNumSel#' : '%#TabNum#')
        let s .= ' ' . i . ' '
        let s .= (i == t ? '%#TabLineSel#' : '%#TabLine#')

        let bufnr = buflist[winnr - 1]
        let file = bufname(bufnr)
        let buftype = getbufvar(bufnr, '&buftype')

        if buftype == 'help'
            let file = 'help:' . fnamemodify(file, ':t:r')

        elseif buftype == 'quickfix'
            let file = 'quickfix'

        elseif buftype == 'nofile'
            if file =~ '\/.'
                let file = substitute(file, '.*\/\ze.', '', '')
            endif

        else
            let file = pathshorten(fnamemodify(file, ':p:~:.'))
            if getbufvar(bufnr, '&modified')
                let file = '+' . file
            endif

        endif

        if file == ''
            let file = '[No Name]'
        endif

        let s .= ' ' . file

        let nwins = tabpagewinnr(i, '$')
        if nwins > 1
            let modified = ''
            for b in buflist
                if getbufvar(b, '&modified') && b != bufnr
                    let modified = '*'
                    break
                endif
            endfor
            let hl = (i == t ? '%#WinNumSel#' : '%#WinNum#')
            let nohl = (i == t ? '%#TabLineSel#' : '%#TabLine#')
            let s .= ' ' . modified . '(' . hl . winnr . nohl . '/' . nwins . ')'
        endif

        if i < tabpagenr('$')
            let s .= ' %#TabLine#|'
        else
            let s .= ' '
        endif

        let i = i + 1

    endwhile

    let s .= '%T%#TabLineFill#%='
    let s .= (tabpagenr('$') > 1 ? '%999XX' : 'X')
    return s

endfunction

" set showtabline=1
highlight! TabNum term=bold,underline cterm=bold,underline ctermfg=1 ctermbg=7 gui=bold,underline guibg=LightGrey
highlight! TabNumSel term=bold,reverse cterm=bold,reverse ctermfg=1 ctermbg=7 gui=bold
highlight! WinNum term=bold,underline cterm=bold,underline ctermfg=11 ctermbg=7 guifg=DarkBlue guibg=LightGrey
highlight! WinNumSel term=bold cterm=bold ctermfg=7 ctermbg=14 guifg=DarkBlue guibg=LightGrey


set tabline=%!MyTabLine()

endif " exists("+showtabline")

""""""""""""""""""""""""""""""""""""""""""""""""" 缩进
au BufEnter,BufNew *.php :set filetype=javascript
au BufEnter,BufNew Jenkinsfile :set filetype=groovy

au FileType groovy setlocal expandtab tabstop=2 shiftwidth=2 autoindent smartindent
au FileType python setlocal expandtab tabstop=4 shiftwidth=4
au FileType html setlocal shiftwidth=2 softtabstop=2 expandtab
au FileType javascript,json setlocal shiftwidth=2 softtabstop=2 expandtab
au FileType vue setlocal expandtab
au Filetype json let g:indentLine_setConceal = 0
